import Block from './block.js';
import Direction from '../lib/direction.js';
import Random from '../lib/random.js';
import Config from '../config/config.js';

// 定义一个蛇类，把跟蛇相关的属性和方法都写在里面
export default class Snake {
    constructor(opt){
        this.direction = Direction.RIGHT;
        this.body = [
            new Block({
                x : Config.BlockSize * 4,
                y: Config.BlockSize,
                color: Random.color()
            }),
            new Block({
                x : Config.BlockSize * 3,
                y: Config.BlockSize,
                color: Random.color()
            }),
            new Block({
                x : Config.BlockSize * 3,
                y: Config.BlockSize,
                color: Random.color()
            })
        ];
    }
    render(parent){
        for(let i =0 ;i < this.body.length; i++){
            this.body[i].init();
            this.body[i].render(parent);
        }
        this.body[0].element.style.zIndex = 99;
        this.body[0].element.innerHTML ='<div class="snakeHead right"></div>';
    }
    move(){
        for(let i = this.body.length - 1; i >= 1; i--){
            var current = this.body[i];
            var prev = this.body[i-1];
            current.x = prev.x;
            current.y = prev.y;
            current.element.style.left = current.x + 'px';
            current.element.style.top = current.y + 'px';
        }

        var head = this.body[0];
        switch(this.direction){          
            case Direction.TOP:
                head.y -= head.height;
            break;
            case Direction.RIGHT:
                head.x += head.width;
            break;
            case Direction.BOTTOM:
                head.y += head.height;
            break;
            case Direction.LEFT:
                head.x -= head.width;
            break;
        }  
        head.element.style.left = head.x +'px';
        head.element.style.top = head.y + 'px';
    } 
    growth(parent){
        var last = this.body[this.body.length - 1];
        var block = new Block();
        block.color = Random.color();
        block.x = last.x;
        block.y = last.y;
        this.body.push(block);
        block.init();
        block.render(parent);
    }
    die(){
        for(var i = 0; i < this.body.length; i++){
            this.body[i].element.parentNode.removeChild(this.body[i].element);
        }
    }
}